package com.zznode.redsun.smartcrm.business.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.zznode.csp.domain.commons.query.JdbcFinderManager;
import com.zznode.csp.domain.commons.query.Page;
import com.zznode.csp.domain.commons.util.MapCreaterBuilder;
import com.zznode.redsun.commons.dto.QueryParameter;
import com.zznode.redsun.commons.utils.GlobalUtils;
import com.zznode.redsun.smartcrm.business.service.ProviderService;

@Service
public class ProviderServiceImpl implements ProviderService {

	@Autowired
	private JdbcFinderManager jdbcFinderManager;

	@Override
	public Page<JSONObject> query(QueryParameter params, int pageNumber, int pageSize) {
		String querySql = jdbcFinderManager.getQueryStringByStatementKey("ProviderService_query");
		MapCreaterBuilder paramBuilder = MapCreaterBuilder.create();
		if (null != params) {
			querySql = params.buildSql(querySql, paramBuilder, null);
		}

		return jdbcFinderManager.queryForPage(querySql + " order by create_date desc", paramBuilder.map(),
				new RowMapper<JSONObject>() {

					@Override
					public JSONObject mapRow(ResultSet rs, int arg1) throws SQLException {
						JSONObject provider = new JSONObject();
						provider.element("id", rs.getLong("id"));
						provider.element("code", rs.getString("code"));
						provider.element("name", rs.getString("name"));
						provider.element("address", rs.getString("address"));
						provider.element("phone", rs.getString("phone"));
						provider.element("contacter", rs.getString("contacter"));
						provider.element("createDateString", GlobalUtils.formartDate(rs.getDate("create_date")));

						return provider;
					}
				}, pageNumber, pageSize);
	}
}
